Alex Liang

[Ruby] 1-D Array to Hash

在實作寄信功能時,需要把一維陣列轉成hash,於是思維還沒轉成ruby的我就寫下這段很初學者的code

原來的code,為了建立mail_list這個hash,花了6行程式碼

app/controllers/goals_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class GoalsController < ApplicationController
...略
def generate_json_params
mail_list = {}
count = 0
for email in @goal.shared_mails
mail_list[count.to_s] = email.mail_addr
count+=1
end

h = JSON.generate({ 'owner' => @goal.owner.name,
'goal' => @goal.title,
'complete_date' => @goal.complete_date,
'email' => mail_list })
end
end

使用Ruby內建的Hash[]可將陣列轉成Hash,再搭配with_index以index當key,一行搞定!

app/controllers/goals_controller.rb
1
2
3
4
5
6
7
8
9
10
class GoalsController < ApplicationController	
...略
def generate_json_params
mail_list = Hash[ @goal.shared_mails.map.with_index {|x, i| [i, x.mail_addr]}]
h = JSON.generate({ 'owner' => @goal.owner.name,
'goal' => @goal.title,
'complete_date' => @goal.complete_date,
'email' => mail_list })
end
end

(沒想到重構一個function居然可以寫3篇文章 XD)

參考來源:
ihower blog文章